<?php

class Core_Model_DbTable_Carts extends YouNet_Db_Table
{
    const STATUS_DEFAULT_SEARCH = -1;
    const STATUS_DELETE     = 0;
	const STATUS_UNREAD     = 1;
	const STATUS_READ       = 10;
    const STATUS_RESOLVED   = 11;
    
    const STATUS_UNIMPORTANT      = 0;
	const STATUS_IMPORTANT    = 1;
	
	const TABLE_NAME = 'carts';
	protected $_name = self::TABLE_NAME;
	protected $_rowClass = 'Core_Model_Cart';
	
	static private $_instance;
	public static function getInstance()
	{
		if (!(self::$_instance instanceof Core_Model_DbTable_Carts))
		{
			self::$_instance = new Core_Model_DbTable_Carts();
		}
		return self::$_instance;
	}
    
    public static function getListStatus()
    {
        return array(
            self::STATUS_DEFAULT_SEARCH => YouNet_Util::translate('LABEL_SELECT_STATUS'),
            self::STATUS_UNREAD     => YouNet_Util::translate('LABEL_STATUS_UNREAD'),
            self::STATUS_READ       => YouNet_Util::translate('LABEL_STATUS_READ'),
            self::STATUS_RESOLVED   => YouNet_Util::translate('LABEL_STATUS_RESOLVED')
        );
    }
    
    public static function getListLowerStatus()
    {
        return array(
            self::STATUS_UNREAD     => YouNet_Util::translate('LABEL_STATUS_LOWER_UNREAD'),
            self::STATUS_READ       => YouNet_Util::translate('LABEL_STATUS_LOWER_READ'),
            self::STATUS_RESOLVED   => YouNet_Util::translate('LABEL_STATUS_LOWER_RESOLVED')
        );
    }
    
    public static function getLowerStatus($case){
        if($case == self::STATUS_DELETE){
            return YouNet_Util::translate('LABEL_STATUS_DELETE');
        }
        else{
            $list_status = self::getListLowerStatus();
            return $list_status[$case];
        }
    }
    
    protected function _getSqlQuery($params)
    {
        $sql = $this->select()->setIntegrityCheck(false)
                ->from(array('cart' => self::TABLE_NAME));
        if(!empty($params['id_page']))
        {
            $sql->where('id_page = ' . $this->_db->quote($params['id_page']));
        }
        if(!empty($params['id_store']))
        {
            $sql->where('id_store = ' . $this->_db->quote($params['id_store']));
        }
        return $sql;
    }

    public function getAllCarts($params)
	{
		$sql = $this->_getSqlQuery($params);
        $sql->joinLeft(array('u' => 'users'), 'u.id = cart.id_user', array('link' => 'u.link'));
        if(!empty($params['status']) && $params['status'] != Core_Model_DbTable_Carts::STATUS_DEFAULT_SEARCH)
        {
            $sql->where('cart.status = ' . $this->_db->quote($params['status']));
        }
        
        if(!empty($params['date_from']))
        {
            $date_from = strtotime($params['date_from']);
            if($date_from){
                $sql->where('cart.time_sent >= ' . $date_from);
            }
        }
        
        if(!empty($params['date_to']))
        {
            $date_to = strtotime($params['date_to']);
            if($date_to){
                $sql->where('cart.time_sent <= ' . $date_to);
            }
        }
        
        $sql->where('cart.status != ' . Core_Model_DbTable_Carts::STATUS_DELETE);
        $sql->order('cart.time_sent DESC');
        return $sql;
	}
    
    public function getOrderHistory($params){
        $id_user = !empty($params['id_user'])?$params['id_user']:-1;
        $id_page = !empty($params['id_page'])?$params['id_page']:-1;
        $id_store = !empty($params['id_store'])?$params['id_store']:-1;
        $sql = $this->_getSqlQuery($params);
        $sql->where('cart.id_user = ?', $id_user);
        $sql->where('cart.id_page = ?', $id_page);
        $sql->where('cart.id_store = ?', $id_store);
        $sql->where('cart.status != ' . Core_Model_DbTable_Carts::STATUS_DELETE);
        $sql->order('cart.time_sent DESC');
        return $sql;
    }
    
    public function getCart($params)
	{
        if(isset($params['id']))
        {
            $sql = $this->_getSqlQuery($params);
            $sql->joinLeft(array('users' => Core_Model_DbTable_Users::TABLE_NAME), 
                    "users.id = cart.id_user", 
                    array('link'));
            $sql->where('cart.status != ' . Core_Model_DbTable_Carts::STATUS_DELETE);
            $sql->where('cart.id = ' . $this->_db->quote($params['id']));
            return $this->fetchRow($sql);
        }
        return null;
	}
    
    public function getHistoryCart($params){
        $id_cart = !empty($params['id_cart'])?$params['id_cart']:null;
        if(isset($id_cart))
        {
            $sql = $this->_getSqlQuery($params);
            $sql->joinLeft(array('users' => Core_Model_DbTable_Users::TABLE_NAME), 
                    "users.id = cart.id_user", 
                    array('link'));
            $sql->where('cart.status != ' . Core_Model_DbTable_Carts::STATUS_DELETE);
            $sql->where('cart.id = ?', $id_cart);
            if(!empty($params['id_user']))
            {
                $sql->where('id_user = ?', $params['id_user']);
            }
            return $this->fetchRow($sql);
        }
        return null;
    }
    
    public function getLatestCart($id_user)
    {
        return $this->fetchRow(array('id_user = ?' => $id_user), 'id DESC');
    }
    
    public function addCart($params, $id_store, $list_products)
    {
        if(!empty($params['id_page']) && !empty($id_store))
        {
            $this->_db->beginTransaction();
            
            $data = array(
                'id_page'       => $params['id_page'],
                'id_store'      => $id_store,
                'user_note'     => $params['user_note'],
                'user_name'     => $params['user_name'],
                'user_email'    => $params['user_email'],
                'user_phone'    => $params['user_phone'],
                'user_location' => $params['user_location'],
                'status'        => self::STATUS_UNREAD,
                'is_important'  => self::STATUS_UNIMPORTANT,
                'time_sent'     => time(),
                'total_price'   => $params['total_price']
            );
            if(!empty($params['id_user']))
            {
                $data['id_user'] = $params['id_user'];
            }
            $id_cart =  $this->insert($data);
            
            Core_Model_DbTable_CartProducts::getInstance()->addCartProducts($list_products, $id_cart);
            
            $this->_db->commit();
            return $id_cart;
        }
        return null;
    }
    
    public function addNote($params)
    {
        if(empty($params['note']))
        {
            $params['note'] = '';
        }
        
        if(!empty($params['id']))
        {
            $params['note'] = preg_replace('/\s+/', " ", trim($params['note']));
            return $this->update(array(
                'note' => $params['note']
            ), array(
                'id = ?' => $params['id']
            ));
        }
        return null;
    }
    
    public function markReadForCart($params)
    {
        if(!empty($params['id']) && !empty($params['id_store']))
        {
            return $this->update(array(
                    'status' => Core_Model_DbTable_Carts::STATUS_READ
                ), array(
                    'status = ?' => Core_Model_DbTable_Carts::STATUS_UNREAD,
                    'id = ?' => $params['id'],
                    'id_store = ?' => $params['id_store']
                ));
        }
        return null;
    }

    public function updateStatusListCarts($params)
    {
        if(!empty($params['id_carts']) && isset($params['to_status']))
        {
            $id_carts = "'" . preg_replace('/,/', "','", $params['id_carts']) . "'";
            $arr_conditions = array("id IN ($id_carts)");
            if(!empty($params['id_store']))
            {
                $arr_conditions['id_store = ?'] = $params['id_store'];
            }
            return $this->update(array(
                'status' => $params['to_status']
            ), $arr_conditions);
        }
        return null;
    }
    
    public function updateStatusImportant($params)
    {
        if(!empty($params['id']) && isset($params['is_important']))
        {
            $arr_conditions = array("id = ?" => $params['id']);
            if(!empty($params['id_store']))
            {
                $arr_conditions['id_store = ?'] = $params['id_store'];
            }
            return $this->update(array(
                'is_important' => $params['is_important']
            ), $arr_conditions);
        }
        return null;
    }
    
    public function getNumberNewOrders($id_store){
        $sql = $this->select()
                ->from(self::TABLE_NAME, array('count' => 'COUNT(*)'))
                ->where('id_store = ?', $id_store)
                ->where('status = ?', self::STATUS_UNREAD);
        $result =  $this->_db->fetchRow($sql);
        if(!empty($result['count'])){
            return $result['count'];
        } else {
            return 0;
        }
    }
}